import image, sensor, lcd, time
from maix import GPIO
from machine import Timer
from machine import UART #串口库函数
from fpioa_manager import fm # GPIO重定向函数
import ubinascii

fm.register(18, fm.fpioa.UART1_TX, force=True)
fm.register(19, fm.fpioa.UART1_RX, force=True) # 设置18、19引脚分别为串口输出、输入引脚

uart = UART(UART.UART1, 115200, 8, 0, 1, timeout=1000, read_buf_len=4096)
tmp = None  # 串口接收到的消息

uart.write('AT+MIPCLOSE\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)

uart.write("AT\r\n")
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)


while True:
    uart.write("AT+CPIN?\r\n")
    tmp = uart.read()
    if(tmp != None):
        if tmp.endswith(b"ERROR: 10\r\n"):
            print("请插入SD卡！！！")
            while True:
                pass
        else:
            print(tmp)
            break
    #time.sleep(1)

uart.write("AT+CGATT?\r\n")
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)

uart.write('AT+SAPBR=3,1,CONTYPE,GPRS\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)

uart.write('AT+SAPBR=3,1,APN,""\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)

#while True:
uart.write('AT+SAPBR=1,1\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)
    #if tmp.endswith("OK\r\n"):
        #break

uart.write('AT+MCONFIG="866289037465624","user","password"\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break
    time.sleep(1)

flag = True
while flag:
    uart.write('AT+MIPSTART="broker.emqx.io","1883"\r\n')
    while flag:
        tmp = uart.read()
        if(tmp != None):
            print(tmp)
            if tmp.endswith("CONNECT OK\r\n"):
                print("已成功接入MQTT服务器")
                flag = False
            elif tmp.endswith("ALREADY CONNECT\r\n"):
                print("设备在执行该命令前就已成功接入MQTT服务器了，请确认是否是你需要它连接的那一个。如果不是，用AT+MIPCLOSE\r\n命令关闭重连")
                uart.write('AT+MIPCLOSE\r\n')
                while True:
                    tmp = uart.read()
                    if(tmp != None):
                        print(tmp)
                        break
                    time.sleep(1)
                #flag = False
            break

uart.write('AT+MCONNECT=1,60\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        if tmp.endswith("CONNACK OK\r\n") or tmp.endswith("CONNECT OK\r\n"):
            break
    time.sleep(1)

uart.write('AT+MSUB="image",0\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        if tmp.startswith("\r\nSUBACK") or tmp.endswith("SUBACK\r\n"):
            break

uart.write('AT+MSUB="finish",0\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        if tmp.startswith("\r\nSUBACK") or tmp.endswith("SUBACK\r\n"):
            break

uart.write('AT+MQTTMSGSET=0\r\n')
while True:
    tmp = uart.read()
    if(tmp != None):
        print(tmp)
        break


def publish(topic, payload):
    uart.write(b'AT+MPUB="' + topic + b'",0,0,"' + payload + b'"\r\n')  # 统一转为Base64文本后进行传输，避免命令截断
    tmp = uart.read()
    if(tmp != None):
        if tmp.endswith("OK\r\n"):
            print("发送成功")
        else:
            print("发送失败:", tmp)

lcd.init()
sensor.reset(dual_buff=False)
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)

block_length = 1024
wait_time = 10
flag = True
# 4G模块及摄像头初始化完成，进行图传任务
while True:
    if flag:
        img = sensor.snapshot()  # 拍摄图像
        lcd.display(img)
        img = img.compress(quality=10)  # 图像压缩
        img_bytes = img.to_bytes()  # 转为字节流
        img_bytes = ubinascii.b2a_base64(img_bytes).strip()
        block = int(len(img_bytes)/block_length)
        print(block)
        for i in range(block):
            publish("image", img_bytes[i*block_length:(i+1)*block_length])
            #time.sleep_ms(wait_time)
        publish("image", img_bytes[block*block_length:])  # 分包传输
        #time.sleep_ms(wait_time)
        publish("finish", "over")  # 结束图传，停止发送，等待小程序回复
        print("发送结束")
        flag = False
    else:
        tmp = uart.read()
        if tmp != None:
            print(tmp)
            if tmp.startswith(b'\r\n+MSUB: "finish"') and tmp.endswith("continue\r\n"):
                flag = True  # 小程序回复"continue"后继续开始发送
